package com.atguigu.tingshu.album.api;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {


    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConstantProperties minioConstantProperties;

    /*
    *  优化：
            为了方便文件管理，可以用时间日期创建目录管理文件
            雪花算法生成文件名称

                - 引入三方依赖： hutool包*/
    @SneakyThrows() //忽略异常
    @Operation(summary = "图片上传文件")
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file)
    {//前端上传文件时  表单项名称必须 和后端接收参数一致 才可以默认接收
        String fileName = new DateTime().toString("yyyy/MM-dd/")
                +IdUtil.getSnowflakeNextId() //雪花算法
                +file.getOriginalFilename().
                substring(file.getOriginalFilename().lastIndexOf("."));
        minioClient.putObject(PutObjectArgs.builder()
                        .bucket(minioConstantProperties.BUCKET_NAME)
                        .object(fileName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                .build());

        String path = MinioConstantProperties.ENDPOINT_URL
                +"/"+MinioConstantProperties.BUCKET_NAME
                + "/"+ fileName;
        return Result.ok(path);
    }
}
